package demo05_topic;

import com.rabbitmq.client.*;
import utils.ConnectionUtil;

import java.io.IOException;
import java.net.URISyntaxException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.TimeoutException;

/**
 * @Description Topic 类型的 Q1 队列消费者
 * @Author shihan
 * @Date 2020/12/26 11:07
 * @Version 1.0
 */
public class TQ1Consumer {

    public static final String Q1_BINDING_KEY = "*.orange.*";

    public static void main(String[] args) throws NoSuchAlgorithmException, KeyManagementException, URISyntaxException, IOException, TimeoutException {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setUri(ConnectionUtil.URI);

        Connection connection = connectionFactory.newConnection();
        Channel channel = connection.createChannel();

        // 声明 Topic 类型的交换器
        channel.exchangeDeclare(TProducer.EXCHANGE_TOPIC_NAME, BuiltinExchangeType.TOPIC);

        // 声明临时队列
        String queueName = channel.queueDeclare().getQueue();

        // 绑定 Queue 和 Exchange 并指明 Binding key
        channel.queueBind(queueName,TProducer.EXCHANGE_TOPIC_NAME,Q1_BINDING_KEY);

        // 监听队列
        channel.basicConsume(queueName, true, new DeliverCallback() {
            @Override
            public void handle(String consumerTag, Delivery message) throws IOException {
                System.out.println(Q1_BINDING_KEY + ": " + new String(message.getBody(),"utf-8"));
            }
        }, new CancelCallback() {
            @Override
            public void handle(String consumerTag) throws IOException {
                // do nothing!
            }
        });

    }

}
